# -*- coding: utf-8 -*-
import json
import sys
import uuid
import requests
import hashlib
import time
from imp import reload

import time

reload(sys)

YOUDAO_URL = 'https://openapi.youdao.com/api'
APP_KEY = '2cbbb5bc4cb34322'
APP_SECRET = 'm6z0fC5GhAUPGW2GN0O7G8ucOoI5jQiA'


def encrypt(signStr):
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(signStr.encode('utf-8'))
    return hash_algorithm.hexdigest()


def truncate(q):
    if q is None:
        return None
    size = len(q)
    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]


def do_request(data):
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    return requests.post(YOUDAO_URL, data=data, headers=headers)


def translation(target: str):

    try:
        # 有道
        data = dict()
        data['from'] = 'ja'
        data['to'] = 'zh-CHS'
        data['signType'] = 'v3'
        current_time = str(int(time.time()))
        data['curtime'] = current_time
        salt = str(uuid.uuid1())
        sign_str = APP_KEY + truncate(target) + salt + current_time + APP_SECRET
        sign = encrypt(sign_str)
        data['appKey'] = APP_KEY
        data['q'] = target
        data['salt'] = salt
        data['sign'] = sign

        response = do_request(data)
        content = json.loads(response.content).get('translation', '')[0]

        # 谷歌
        url = 'http://translate.google.cn/translate_a/single?'
        param = f'client=at&sl=ja&tl=zh-CN&dt=t&q={target}'
        # from urllib.parse import urlencode
        # param = urlencode(param)
        r = requests.get(url + param)
        google_content = json.loads(r.text)[0][0][0]
        result = {'youdao': f'{content}', 'google': f'{google_content}'}
    except Exception as e:
        return {'youdao': '', 'google': ''}

    return result
